/**
 * Created by wxb on 2016/10/12.
 */
(function () {
  'use strict';

  angular.module('BlurAdmin.theme.components')
    .controller('ApkUploadCtrl', ApkUploadCtrl);

  /** @ngInject */
  function ApkUploadCtrl($scope, $qupload, $log, qiniuToken, rfc4122) {
    var token;
    var innerKey;

    if ($scope.ARmagicLibrary) {
      qiniuToken.cooperationToken().then(function (data) {
        token = data.data.token;
      });
      innerKey = 'hm/ar/apk/'
    }
    else {
      qiniuToken.apkToken().then(function (data) {
        token = data.data.token;
      });
    }

    var apkBaseUrl = qiniuToken.apkBaseUrl();

    $scope.apkSelectFiles = [];
    $scope.apkUploading = false;

    var start = function (index) {
      $scope.apkSelectFiles[index].progress = {
        p: 0
      };
      $scope.apkSelectFiles[index].upload = $qupload.upload({
        key: ($scope.key || innerKey) + rfc4122.v4() + '.' + $scope.apkSelectFiles[index].file.name.split(".").pop(),
        file: $scope.apkSelectFiles[index].file,
        token: token
      });
      $scope.apkSelectFiles[index].upload.then(function (response) {
        $log.info(response);
        $scope.apkUrl = apkBaseUrl + response.key;
        $scope.formData.apkUrl = response.key;
        $scope.formData.size = ($scope.apkSelectFiles[index].file.size/1024/1024).toFixed(2) + 'MB';
        $scope.formData.rawSize = $scope.apkSelectFiles[index].file.size;

      }, function (response) {
        $log.info(response);
      }, function (evt) {
        $scope.apkSelectFiles[index].progress.p = Math.floor(100 * evt.loaded / evt.totalSize);
        $scope.apkProgressbarValue = $scope.apkSelectFiles[index].progress.p;
        if (evt) {
          $scope.apkUploading = true;
        }
        // if ($scope.apkSelectFiles[index].progress.p === 100) {
        //   $scope.uploading = false;
        // }

      });
    };

    $scope.apkAbort = function (index) {
      $scope.apkSelectFiles[index].upload.abort();
      $scope.apkSelectFiles.splice(index, 1);
      $scope.apkProgressbarValue = undefined;
      $scope.apkUploading = false;
    };

    $scope.onApkSelect = function ($files) {
      var offsetx = $scope.apkSelectFiles.length;
      if (offsetx > 0 && $scope.apkProgressbarValue && $scope.apkProgressbarValue > 0 && $scope.apkProgressbarValue < 100) {
        $scope.apkAbort(offsetx-1);
      }
      for (var i = 0; i < $files.length; i++) {
        $scope.apkSelectFiles[i + offsetx] = {
          file: $files[i]
        };
        $scope.abortIndex = i + offsetx;
        start(i + offsetx);
      }
    };


  }

})();










